IF EXISTS (SELECT * FROM SYSOBJECTS WHERE ID = OBJECT_ID('PaintTagBatchUpdate','P'))
    DROP PROCEDURE PaintTagBatchUpdate
GO
/*
 * Designer:     Kevin
 * Description:    
 * Created:      03/10/2011
 * History:
 * =============================================================================
 * Author      DateTime        Alter Description
 * =============================================================================
 */

CREATE PROCEDURE PaintTagBatchUpdate
(
	@PaintingId int,
	@Tags nvarchar(max)
)
AS
BEGIN

	if @Tags is null or @Tags=''
	begin
		return
	end
	
	declare @TempTag table(
		TagId int,
		TagValue nvarchar(100)
	)

	insert into @TempTag(
		TagValue
	)
	select Item as TagValue
	from FunStringSplit(@Tags, ',')
	
	insert into Tag(
		[value]
	)
	select TagValue
	from @TempTag TempTag
	left join Tag on TempTag.TagValue=Tag.[value]
	where Tag.[value] is null
	
	update TempTag
	set 
		TagId=Tag.Tag_id
	from 
		@TempTag TempTag
		inner join Tag on TempTag.TagValue=Tag.[value]
				
	update Tag
	set count_of_paint=count_of_paint+1
	from Tag 
	inner join @TempTag TempTag on Tag.Tag_Id = TempTag.TagId
	left join painting_Tag on TempTag.TagId=painting_Tag.Tag_id and painting_Tag.painting_id=@PaintingId
	where painting_Tag.Tag_id is null
	
	insert into painting_Tag (
		painting_id,
		Tag_id
	)
	select 
		@PaintingId,
		TempTag.TagId
	from @TempTag TempTag
	left join painting_Tag on TempTag.TagId=painting_Tag.Tag_id and painting_Tag.painting_id=@PaintingId
	where painting_Tag.Tag_id is null
	
	update Tag
	set count_of_paint=count_of_paint-1
	from Tag 
	inner join painting_Tag on Tag.Tag_id=painting_Tag.Tag_id 
	left join @TempTag TempTag on TempTag.TagId=painting_Tag.Tag_id 
	where 
		TempTag.TagId is null
		and painting_Tag.painting_id=@PaintingId
	
	delete from painting_Tag
	from painting_Tag
	left join @TempTag TempTag on TempTag.TagId=painting_Tag.Tag_id 
	where 
		TempTag.TagId is null
		and painting_Tag.painting_id=@PaintingId
END
GO